package cn.work.control;

import cn.work.service.BatchOperationService;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebServlet(name = "BatchOperationServlet", value = "/BatchOperationServlet")
public class BatchOperationServlet extends HttpServlet {

    private final BatchOperationService batchOperationService = new BatchOperationService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json; charset=UTF-8");

        // 从请求中解析 JSON 数据
        String json = request.getReader().lines().collect(Collectors.joining());
        System.out.println("接收到的 JSON 数据: " + json);
        Gson gson = new Gson();
        Map<String, Object> requestData = gson.fromJson(json, Map.class);
        System.out.println("解析后的数据: " + requestData); // 调试用
        // 获取 ids 和 action 参数
        String action = (String) requestData.get("action");

        // 转换 Double 类型的 IDs 为 Integer
        List<String> idsString = (List<String>) requestData.get("ids");

// 将 String 转换为 Integer
        List<Integer> ids = idsString.stream()
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        // 调用服务层处理批量操作
        Map<String, Object> result = batchOperationService.processBatchOperation(ids, action);

        // 返回结果为 JSON 格式
        response.getWriter().write(gson.toJson(result));
    }
}
